import React, { useState, useEffect, useRef } from 'react';
import {
    Form,
    Button,
    Input,
    Affix,
    Select,
    message,
    Space,
    Switch,
    Drawer,
    Checkbox,
    Row,
    Col,
    InputNumber,
    Modal,
} from 'antd';
import { MinusCircleOutlined, PlusCircleOutlined } from '@ant-design/icons';
import cmdbres from '@/data/cmdbres';
import request from '@/utils/request';
import regexpUtil from '@/utils/regexpUtil';
import hcpUtils from '@/utils/hcpUtils';

const user = hcpUtils.getUser();
const { uniqueIdentificationRegexp, commonNameRegexp, commonCodeRegexp } = regexpUtil;
const CreateField = ({ history, visible, setVisible, onCreateFinish, moduleId, propertyGroup }) => {
    const [loading, setLoading] = useState(false);
    const [fieldType, setFieldType] = useState([]);
    const [selectTypeValue, setSelectTypeValue] = useState('');
    const [form] = Form.useForm();

    useEffect(() => {
        if (visible) {
            queryModelPropertyType();
        }
    }, [visible]);

    const queryModelPropertyType = async () => {
        try {
            let res = await request({
                ...cmdbres.queryModelPropertyType,
                params: {},
            });
            if (res && res.code == 200) {
                setFieldType(res.data);
            }
        } catch (error) {
            setFieldType([]);
        }
    };

    const onFinish = async () => {
        const fieldsValue = form.getFieldsValue();
        setLoading(true);
        let param = {
            cmModuleId: moduleId,
            propertyKey: fieldsValue.propertyKey,
            propertyName: fieldsValue.propertyName,
            propertyGroup: propertyGroup,
            propertyType: selectTypeValue,
            woIsEdit: fieldsValue.woIs?.includes('woIsEdit') ? 1 : 0,
            woIsRequired: fieldsValue.woIs?.includes('woIsRequired') ? 1 : 0,
            woIsHidden: fieldsValue.woIs?.includes('woIsHidden') ? 0 : 1, //字段意思为“是否隐藏”，页面展示“是否需要”，取值时需要取反
            woIsExoprtTemplate: fieldsValue.woIs?.includes('woIsExoprtTemplate') ? 'Y' : 'N',
            description: fieldsValue.description || '',
            ruleDescription: fieldsValue.ruleDescription || '',
            regexExpression: fieldsValue.regexExpression || '',
            woIsSystem: 0, //0为非系统属性，默认为0
            author: user.staffName,
        };

        if (selectTypeValue == 'enum') {
            let enumValueArr = [];
            for (let item of fieldsValue.propertyEnumValue) {
                let enumValue = [item.key, item.value];
                enumValueArr.push(enumValue);
            }
            param['propertyEnumValue'] = JSON.stringify(Object.fromEntries(enumValueArr));
        }

        if (fieldsValue.unit) param['unit'] = fieldsValue.unit;

        let res = await request({
            ...cmdbres.createModelProperty,
            data: param,
        });
        setLoading(false);
        if (res && res.code == 200) {
            setVisible(false);
            form.resetFields();
            message.success('保存成功！');
            if (typeof onCreateFinish == 'function') onCreateFinish(res);
        } else {
            if (res) message.error(res.msg);
        }
    };

    const changeType = (value) => {
        setSelectTypeValue(value);
    };

    const handleClose = () => {
        setVisible(false);
        form.resetFields();
    };

    return (
        <Modal
            title="新增字段"
            className="hcp-modal-md"
            width={600}
            visible={visible}
            footer={null}
            onCancel={handleClose}
            destroyOnClose
            maskClosable={false}
            afterClose={() => {
                form.resetFields();
            }}
        >
            <Form form={form} labelCol={{ span: 5 }} wrapperCol={{ span: 18 }} name="basic" onFinish={onFinish}>
                <Form.Item
                    label="唯一标识"
                    name="propertyKey"
                    required
                    rules={[
                        {
                            required: true,
                            message: '唯一标识不能为空',
                        },
                        uniqueIdentificationRegexp(256),
                    ]}
                    // extra={
                    //     <p style={{ color: "#999999" }}>
                    //         请填写以字母开头，数字、字母、下划线，横线的组合
                    //     </p>
                    // }
                    // style={{ marginBottom: 5 }}
                >
                    <Input placeholder="请输入唯一标识" maxLength={256} />
                </Form.Item>
                <Form.Item label="名称" name="propertyName" required>
                    <Input placeholder="请输入字段名称" maxLength={50} />
                </Form.Item>
                <Form.Item label="字段类型" name="propertyType" required>
                    <Select placeholder="请选择" style={{ width: '100%', marginRight: 10 }} onChange={changeType}>
                        {fieldType.length == 0
                            ? null
                            : fieldType.map((item, index) => (
                                  <Select.Option key={index} value={item.name}>
                                      {item.describe}
                                  </Select.Option>
                              ))}
                    </Select>
                </Form.Item>
                <Form.Item name="woIs" label="字段设置">
                    <Checkbox.Group style={{ width: '80%' }}>
                        <Row>
                            <Col span={8}>
                                <Checkbox value="woIsEdit" style={{ lineHeight: '32px' }}>
                                    可编辑
                                </Checkbox>
                            </Col>
                            <Col span={8}>
                                <Checkbox value="woIsRequired" style={{ lineHeight: '32px' }}>
                                    必填
                                </Checkbox>
                            </Col>
                            <Col span={8}>
                                <Checkbox value="woIsHidden" style={{ lineHeight: '32px' }}>
                                    列表展示
                                </Checkbox>
                            </Col>
                            <Col span={8}>
                                <Checkbox value="woIsExoprtTemplate" style={{ lineHeight: '32px' }}>
                                    是否支持模板导出
                                </Checkbox>
                            </Col>
                        </Row>
                    </Checkbox.Group>
                </Form.Item>
                {selectTypeValue == 'enum' ? (
                    <Form.List
                        name="propertyEnumValue"
                        initialValue={['']}
                        rules={[
                            {
                                validator: async (_, propertyEnumValue) => {
                                    if (!propertyEnumValue || propertyEnumValue.length < 1) {
                                        return Promise.reject(new Error('该项为必填项'));
                                    }
                                },
                            },
                        ]}
                    >
                        {(fields, { add, remove }) => (
                            <div className="property-enum">
                                {fields.map((field, index) => (
                                    <Form.Item
                                        label={index === 0 ? '枚举值' : ''}
                                        style={index > 0 ? { width: '100%', marginLeft: '20.833%' } : {}}
                                        required
                                        name={field.name}
                                        key={field.key}
                                    >
                                        <Form.Item
                                            {...field}
                                            name={[field.name, 'key']}
                                            key={(field.key, 'key')}
                                            validateTrigger={['onChange', 'onBlur']}
                                            rules={[
                                                {
                                                    required: true,
                                                    whitespace: true,
                                                    message: '该项为必填项',
                                                },
                                            ]}
                                            noStyle
                                        >
                                            <Input
                                                placeholder="请输入"
                                                style={{ width: '120px', marginRight: '8px' }}
                                            />
                                        </Form.Item>
                                        <Form.Item
                                            {...field}
                                            name={[field.name, 'value']}
                                            key={(field.key, 'value')}
                                            validateTrigger={['onChange', 'onBlur']}
                                            rules={[
                                                {
                                                    required: true,
                                                    whitespace: true,
                                                    message: '该项为必填项',
                                                },
                                            ]}
                                            noStyle
                                        >
                                            <Input
                                                placeholder="请输入"
                                                style={{ width: '180px', marginRight: '8px' }}
                                            />
                                        </Form.Item>

                                        {fields.length > 1 ? (
                                            <MinusCircleOutlined
                                                className="dynamic-delete-button"
                                                onClick={() => remove(field.name)}
                                            />
                                        ) : null}
                                        {index == fields.length - 1 ? (
                                            <PlusCircleOutlined onClick={() => add()} />
                                        ) : null}
                                    </Form.Item>
                                ))}
                            </div>
                        )}
                    </Form.List>
                ) : null}
                {selectTypeValue == 'number' || selectTypeValue == 'float' ? (
                    <>
                        {/* <Form.Item label="最大值" name="max" >
                        <InputNumber placeholder="最大值"/>
                    </Form.Item>
                    <Form.Item label="最小值" name="min" >
                        <InputNumber placeholder="请输入单位"/>
                    </Form.Item> */}
                        <Form.Item label="单位" name="unit">
                            <Input placeholder="请输入单位" maxLength={64} />
                        </Form.Item>
                    </>
                ) : null}
                <Form.Item label="用户提示" name="description">
                    <Input.TextArea />
                </Form.Item>
                <Form.Item label="校验规则" name="ruleDescription">
                    <Input.TextArea />
                </Form.Item>
                <Form.Item label="正则表达式" name="regexExpression">
                    <Input.TextArea />
                </Form.Item>
                <div className="hcp-modal-body-footer">
                    <Form.Item wrapperCol={{ span: 24 }}>
                        <Button onClick={handleClose}>取消</Button>
                        <Button type="primary" htmlType="submit" loading={loading}>
                            确认
                        </Button>
                    </Form.Item>
                </div>
            </Form>
        </Modal>
    );
};

export default CreateField;
